//
//  YWFinishTroubleMissionTableViewController.m
//  maintain
//
//  Created by Kyo on 16/9/22.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWFinishTroubleMissionTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "UIScrollView+EmptyDataSet.h"
#import "NSDate+YYAdd.h"
#import "MJExtension.h"
#import "MJRefresh.h"
#import "YWCommonTool.h"

#import "YWPush.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWTroubleMissionCell.h"

#import "YWNotifyManager.h"
#import "YWMissionManager.h"
#import "YWTemTroubleDetailTableViewController.h"
#import "YWCirculationDetailViewController.h"
#import "YWTroubleMissionModel.h"
#import "YWTroubleMissionManager.h"
#import "YWReportTroubleModel.h"

@interface YWFinishTroubleMissionTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>{
    BOOL isLoadData;
    NSUInteger page;
}
@property (nonatomic, strong) NSMutableArray* sourceDatas;
@end

@implementation YWFinishTroubleMissionTableViewController
//- (instancetype)init{
//    return [super initWithStyle:UITableViewStyleGrouped];
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    isLoadData = NO;
    
    [self setupNotifications];
    [self setupTableView];
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if (isLoadData==NO) {
        isLoadData = YES;
        page=1;
        _sourceDatas = nil;
        [self.tableView reloadData];
    }
}

- (void)setupNotifications{
    [[YWNotifyManager shareManager] addMissionFinishedObserver:self selector:@selector(refreshTableView:)];
    [[YWNotifyManager shareManager] addMissionProgressObserver:self selector:@selector(refreshTableView:)];
    [[YWNotifyManager shareManager] addRequestTroubleMissionObserver:self selector:@selector(refreshTableView:)];
    [[YWNotifyManager shareManager] addDeleteMissionObserver:self selector:@selector(refreshTableView:)];
}

- (void)setupTableView{
    [self.tableView registerClass:[YWTroubleMissionCell class] forCellReuseIdentifier:YWTroubleMissionCellIdentifier];
    
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.sectionFooterHeight = 0.01f;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
}

- (NSArray*)sourceDatas
{
    if (!_sourceDatas) {
        _sourceDatas = [NSMutableArray array];
        [_sourceDatas addObjectsFromArray:[[YWTroubleMissionManager shareManager] troubleMissionModelWithStatus:YWTroubleMissionStatusFinish page:page]];
    }
    return _sourceDatas;
}

#pragma mark test
- (void)refreshTop
{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}
- (void)requestData:(YWTableViewFreshType)refreshType
{
    YWWeakSelf(weakSelf)
    dispatch_group_t group = dispatch_group_create();
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        __block NSInteger dataCount = 0;
//        __block NSTimeInterval createTime = 0;
        if (refreshType == YWTableViewFreshTypeUp) {
            page++;
        }
        
        dispatch_group_enter(group);
        [[YWTroubleMissionManager shareManager] requestTroubleMissionWithPage:page pageSize:10 troubleStatus:YWTroubleMissionStatusFinish completeBlock:^(NSInteger count) {
            dataCount += count;
            dispatch_group_leave(group);
        }];
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }
            else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            weakSelf.sourceDatas = nil;
            [weakSelf.tableView reloadData];
        });
    });
}

#pragma mark - UITableViewDataSource mothods
//- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
//{
//    return [tableView fd_heightForCellWithIdentifier:YWTroubleMissionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWTroubleMissionCell *cell) {
//        [self configureCell:cell atIndexPath:indexPath];
//    }];
//}

- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return [self.sourceDatas count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.sourceDatas[section] count];
}

- (void)configureCell:(YWTroubleMissionCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    YWTroubleMissionModel* mission = self.sourceDatas[indexPath.section][indexPath.row];
    cell.fd_enforceFrameLayout = NO;
    cell.troubleMissionModel = mission;
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    
    YWTroubleMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTroubleMissionCellIdentifier];
    [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWFinishTroubleMissionTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *temp = self.sourceDatas[section];
    YWTroubleMissionModel* troubleMission = temp.count ? temp[0] : nil;
    NSString *time = [YWCommonTool showChineseFormatterDate:troubleMission.updateTime/1000];
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:troubleMission.updateTime/1000].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
    return title;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWTroubleMissionModel* troubleMission = self.sourceDatas[indexPath.section][indexPath.row];
    if (troubleMission.trouble.troubleId<=0 && troubleMission.troubleStatus == YWTroubleMissionStatusFinish) {
        YWTemTroubleDetailTableViewController *tempTroubleVC = [[YWTemTroubleDetailTableViewController alloc] init];
        tempTroubleVC.troubleMissionModel = troubleMission;
        [self.navigationController pushViewController:tempTroubleVC animated:YES];
    }else{
        YWCirculationDetailViewController *circulationVetailVC = [[YWCirculationDetailViewController alloc] init];
        circulationVetailVC.troubleMissionModel = troubleMission;
        [self.navigationController pushViewController:circulationVetailVC animated:YES];
    }
//    if (troubleMission.maintenanceTypeId == YWMaintenanceTypeTrouble) {
//        
//    }
}
- (void)refreshTableView:(id)sender{
    _sourceDatas = nil;
    [self.tableView reloadData];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
